import 'package:flutter/material.dart';
import 'package:word_range_client/widgets/general/PartingLine.dart';

import '../../pojo/vo/ConditionVo.dart';
import '../../pojo/vo/EventVo.dart';
import '../../viewModels/EventViewModel.dart';
import '../../widgets/general/MsgDialog.dart';
import '../../widgets/general/Toastification.dart';

class EventDetailView extends StatefulWidget {
  const EventDetailView({super.key, required this.eventVo});

  final EventVo eventVo;

  @override
  State<EventDetailView> createState() => _EventDetailViewState();
}

class _EventDetailViewState extends State<EventDetailView> {
  Future<void> showConfirmationDialog() async {
    MsgDialog dialog = MsgDialog(context);
    Toastification toastification = Toastification(context: context);
    bool? confirm = await dialog.showDefaultDialog("确认参加活动吗");
    if(confirm == true){
      toastification.showSuccess("这里就当参加成功了");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.eventVo.title!),
      ),
      body: EventDetailViewBody(eventVo: widget.eventVo,),
      floatingActionButton: SizedBox(
        width: MediaQuery.of(context).size.width * 0.55,
        height: 50,
        child: FloatingActionButton(
          onPressed: showConfirmationDialog,
          child: const Text(
            "立即参加",
            style: TextStyle(
                fontSize: 17,
                color: Colors.white
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}

class EventDetailViewBody extends StatefulWidget {
  const EventDetailViewBody({super.key, required this.eventVo});

  final EventVo eventVo;

  @override
  State<EventDetailViewBody> createState() => _EventDetailViewBodyState();
}

class _EventDetailViewBodyState extends State<EventDetailViewBody> {

  late double _yOffset = 20;
  bool _isLoading = true; // 新增一个布尔变量来跟踪加载状态

  @override
  void initState() {
    super.initState();
    Future.delayed(const Duration(milliseconds: 600),(){
      setState(() {
        _yOffset = 0;
        _isLoading = false;
      });
    });
  }

  Image _initImage(){
    return widget.eventVo.imageUrl == null ?
    Image.asset("assets/images/Default_event_picture.png",fit: BoxFit.cover,):
    Image.network(widget.eventVo.imageUrl!,fit: BoxFit.cover,);
  }

  // 剩余时间提示
  Widget _initRemainingDaysTips(){
    String? endDate = widget.eventVo.endDate;
    if(endDate != null){
      DateTime endDateTime = DateTime.parse(endDate);
      DateTime now = DateTime.now();
      Duration difference = endDateTime.difference(now);
      int remainingDays = difference.inDays;
      return _RemainingDaysTips(remainingDay: remainingDays);
    }
    return const SizedBox();
  }

  // 加载提示
  Widget _buildLoadingIndicator() {
    return Column(
      children: [
        ClipRRect(
          borderRadius: const BorderRadius.all(Radius.circular(10.0)),
          child: LinearProgressIndicator(
            color: Theme.of(context).colorScheme.primary,
          ),
        ),
        const SizedBox(height: 10,),
        const Text("加载中")
      ],
    );
  }

  // 活动详情内容卡片
  Widget _buildDetailCard(){
    return Card(
      elevation: 10, // 增加阴影效果
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15) // 增加圆角
      ),
      margin: const EdgeInsets.all(10), // 增加外边距
      child: Padding(
        padding: const EdgeInsets.all(20), // 增加内边距
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.eventVo.title!,
                      style: const TextStyle(
                        fontSize: 28,
                        fontWeight: FontWeight.w700,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 8), // 增加间距
                    Text(
                      widget.eventVo.subTitle!,
                      style: const TextStyle(
                        fontSize: 18,
                        color: Colors.black54,
                      ),
                    ),
                  ],
                ),
                _initRemainingDaysTips(),
              ],
            ),
            const SizedBox(
              height: 20,
              child: Divider(
                height: 1.0,
                color: Colors.black38,
              ),
            ),
            Text(
              widget.eventVo.detail!,
              style: const TextStyle(
                fontSize: 16,
                color: Colors.black87,
                height: 1.5, // 增加行高
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildConditionCard(){
    return FutureBuilder<List<ConditionVo>>(
      future: EventViewModel.getConditionListByEvent(widget.eventVo.id!),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('暂无活动条件'));
        } else {
          return SizedBox(
            width: double.infinity,
            child: Card(
              elevation: 5,
              margin: const EdgeInsets.all(10), // 增加外边距
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)
              ),
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text("活动条件", style: TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.w600
                    )),
                    const PartingLine(),
                    ...snapshot.data!.map((condition) => Text(
                      '- ${condition.name}',
                      style: const TextStyle(fontSize: 17),
                    )).toList(),
                  ],
                ),
              ),
            ),
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        SizedBox(
          width: MediaQuery.of(context).size.width,
          height: 250,
          child: Hero(
            tag: "event_${widget.eventVo.id}_image",
            child: _initImage(),
          ),
        ),
        AnimatedContainer(
          margin: const EdgeInsets.fromLTRB(8, 10, 8, 80),
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
          transform: Matrix4.translationValues(0, _isLoading ? _yOffset : 0, 0),
          child: _isLoading ?
          _buildLoadingIndicator() :   // 加载提示
          Column(
            children: [
              _buildConditionCard(),
              _buildDetailCard(),
            ],
          )
        )
      ],
    );
  }
}

class _RemainingDaysTips extends StatelessWidget {
  const _RemainingDaysTips({super.key, required this.remainingDay});

  final int remainingDay;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 88,
      height: 28,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: remainingDay <= 5 ?
        Theme.of(context).colorScheme.error:
        Theme.of(context).colorScheme.primary,
        borderRadius: BorderRadius.circular(15),
      ),
      child: Text(
        "剩余$remainingDay天",
        style: TextStyle(
            color: Theme.of(context).colorScheme.background
        ) ,
      ),
    );
  }
}

